import {setToken, setRefreshToken, removeToken, removeRefreshToken} from '@/util/auth'
import {Message} from 'element-ui'
import {setStore, getStore} from '@/util/store'
import {isURL, validatenull} from '@/util/validate'
import {deepClone} from '@/util/util'
import website from '@/config/website'
import {loginByUsername, loginBySocial, loginByToken, logout, refreshToken, getButtons} from '@/api/user' //getUserInfo
import {getTopMenu, getRoutes} from '@/api/system/menu'
import md5 from 'js-md5'

function addPath(ele, first) {
  const menu = website.menu;
  const propsConfig = menu.props;
  const propsDefault = {
    label: propsConfig.label || 'name',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  const icon = ele[propsDefault.icon];
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
  if (!isChild) ele[propsDefault.children] = [];
  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
  } else {
    ele[propsDefault.children].forEach(child => {
      addPath(child);
    })
  }

}

const user = {
  state: {
    tenantId: getStore({name: 'tenantId'}) || '',
    userInfo: getStore({name: 'userInfo'}) || [],
    permission: getStore({name: 'permission'}) || {},
    roles: getStore({name:'roles'}) || {},
    menu: getStore({name: 'menu'}) || [],
    menuId: getStore({name: 'menuId'}) || [],
    menuAll: getStore({name: 'menuAll'}) || [],
    token: getStore({name: 'token'}) || '',
    refreshToken: getStore({name: 'refreshToken'}) || '',
    oc: getStore({name: 'oc'}) || false,
    offer: getStore({name: 'offer'}) || '',
  },
  actions: {
    //根据用户名登录
    LoginByUsername({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        loginByUsername(userInfo.username, md5(userInfo.password), userInfo.type, userInfo.key, userInfo.code).then(res => {
          const data = res.data;
          if (data.error_description) {
            Message({
              message: data.error_description,
              type: 'error'
            })
          } else {
            commit('SET_ROLES',data.role_name)
            commit('SET_OFFER', userInfo.offerId)
            commit('SET_OC', userInfo.oc)
            commit('SET_TOKEN', data.access_token);
            commit('SET_REFRESH_TOKEN', data.refresh_token);
            commit('SET_TENANT_ID', data.tenant_id);
            commit('SET_USER_INFO', data);
            commit('DEL_ALL_TAG');
            commit('CLEAR_LOCK');
          }
          resolve();
        }).catch(error => {
          reject(error);
        })
      })
    },
    //根据Token登录
    LoginByToken({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        loginByToken(userInfo.tokenKey).then(res => {
          const data = res.data;
          if (data.error_description) {
            Message({
              message: data.error_description,
              type: 'error'
            })
          } else {
            commit('SET_ROLES',data.role_name)
            commit('SET_OC', userInfo.oc)
            commit('SET_TOKEN', data.access_token);
            commit('SET_REFRESH_TOKEN', data.refresh_token);
            commit('SET_TENANT_ID', data.tenant_id);
            commit('SET_USER_INFO', data);
            commit('DEL_ALL_TAG');
            commit('CLEAR_LOCK');
          }
          resolve(res);
        }).catch(error => {
          reject(error);
        })
      })
    },
    //根据手机号登录
    LoginByPhone({commit}, userInfo) {
      return new Promise((resolve) => {
        loginByUsername(userInfo.phone, userInfo.code).then(res => {
          const data = res.data.data;
          commit('SET_TOKEN', data);
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          resolve();
        })
      })
    },
    //根据第三方信息登录
    LoginBySocial({commit}, userInfo) {
      return new Promise((resolve) => {
        loginBySocial(userInfo.tenantId, userInfo.source, userInfo.code, userInfo.state).then(res => {
          const data = res.data;
          if (data.error_description) {
            Message({
              message: data.error_description,
              type: 'error'
            })
          } else {
            commit('SET_TOKEN', data.access_token);
            commit('SET_REFRESH_TOKEN', data.refresh_token);
            commit('SET_USER_INFO', data);
            commit('DEL_ALL_TAG');
            commit('CLEAR_LOCK');
          }
          resolve();
        })
      })
    },
    // //获取用户信息
    // GetUserInfo({commit}) {
    //   return new Promise((resolve, reject) => {
    //     getUserInfo().then((res) => {
    //       const data = res.data.data;
    //       commit('SET_ROLES', data.roles);
    //       resolve(data);
    //     }).catch(err => {
    //       reject(err);
    //     })
    //   })
    // },
    //刷新token
    refreshToken({state, commit}) {
      window.console.log('handle refresh token')
      return new Promise((resolve, reject) => {
        refreshToken(state.refreshToken, state.tenantId).then(res => {
          const data = res.data;
          commit('SET_TOKEN', data.access_token);
          commit('SET_REFRESH_TOKEN', data.refresh_token);
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     *
     * @param commit
     * @returns {Promise<unknown>}
     * @constructor
     */
    refreshTokenLogin({commit},dataList){
      window.console.log('handle refresh token')
      return new Promise((resolve, reject) => {
        refreshToken(dataList.refreshToken, dataList.tenantId).then(res => {
          const data = res.data;
          commit('SET_TOKEN', data.access_token);
          commit('SET_REFRESH_TOKEN', data.refresh_token);
          commit('SET_ROLES',data.role_name)
          commit('SET_OFFER', dataList.offerId)
          commit('SET_OC',dataList.offerId ? true : false)
          commit('SET_TENANT_ID', data.tenant_id);
          commit('SET_USER_INFO', data);
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({commit}) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '');
          commit('SET_MENU', []);
          commit('SET_MENU_ID', {});
          commit('SET_MENU_ALL', []);
          commit('SET_ROLES', []);
          commit('SET_TAG_LIST', []);
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          removeToken();
          removeRefreshToken();
          resolve();
          sessionStorage.setItem('store', JSON.stringify({}))
        }).catch(error => {
          reject(error)
        })
      })
    },
    //注销session
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_MENU_ID', {});
        commit('SET_MENU_ALL', []);
        commit('SET_MENU', []);
        commit('SET_OFFER', '');
        commit('SET_ROLES', []);
        commit('SET_TAG_LIST', []);
        commit('DEL_ALL_TAG');
        commit('CLEAR_LOCK');
        this.$router.replace({path: '/login'});
        location.reload();
        removeToken();
        removeRefreshToken();
        resolve();
      })
    },
    //获取顶部菜单
    GetTopMenu() {
      return new Promise(resolve => {
        getTopMenu().then((res) => {
          const data = res.data.data || [];
          resolve(data)
        })
      })
    },
    //获取系统菜单
    GetMenu({commit, dispatch}, topMenuId) {
      var platform = 'bc';
      if (getStore({name: 'oc'})) {
        platform = 'oc';
      }
      return new Promise(resolve => {
        getRoutes(topMenuId, platform).then((res) => {
          let data = res.data.data
          /*data.forEach(menu => {
            if (menu.code === 'desk' && store.state.user.userInfo.is_agency === 0) {
              let flag = menu.children.forEach(child => {
                if (child.code === 'business_customer') {
                  child.name = '合作伙伴'
                  return true
                }
              })
              if (flag) return true
            }
          })*/
          let menu = deepClone(data);
          menu.forEach(ele => {
            addPath(ele, true);
          });
          commit('SET_MENU_ALL', menu)
          commit('SET_MENU', menu)
          dispatch('GetButtons');
          resolve(menu)
        })

      })
    },
    //获取系统按钮
    GetButtons({commit}) {
      return new Promise((resolve) => {
        getButtons().then(res => {
          let data = res.data.data;
          /*if (store.state.user.userInfo.is_agency === 0) {
            data.forEach(menu => {
              if (menu.code === 'business_customer') {
                menu.children.forEach((child, index) => {
                  if (child.code === 'customer_add') {
                    menu.children.splice(index, 3)
                    console.log(menu)
                  }
                })
              }
            })
          }*/
          commit('SET_PERMISSION', data);
          resolve();
        })
      })
    },
    //修改offer
    ocOffer({commit}, offerId) {
      return new Promise((() => {
        commit('SET_OFFER', offerId)
      }))
    }
  },
  mutations: {
    SET_OC: (state, oc) => {
      state.oc = oc
      setStore({name: 'oc', content: state.oc})
    },
    SET_OFFER: (state, offerId) => {
      state.offer = offerId
      setStore({name: 'offer', content: state.offer})
    },
    SET_OFFER_NAME: (state, offerName) => {
      state.offerName = offerName
      setStore({name: 'offerName', content: state.offerName})
    },
    SET_TOKEN: (state, token) => {
      setToken(token);
      state.token = token;
      setStore({name: 'token', content: state.token})
    },
    SET_MENU_ID(state, menuId) {
      state.menuId = menuId;
      setStore({name: 'menuId', content: state.menuId})
    },
    SET_MENU_ALL: (state, menuAll) => {
      state.menuAll = menuAll
      setStore({name: 'menuAll', content: state.menuAll})
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({name: 'menu', content: state.menu})
      if (validatenull(menu)) return;
      //合并动态路由去重
      let menuAll = state.menuAll;
      menuAll = menuAll.concat(menu).reverse();
      let newMenu = [];
      for (let item1 of menuAll) {
        let flag = true;
        for (let item2 of newMenu) {
          if (item1.name === item2.name || item1.path === item2.path) {
            flag = false;
          }
        }
        if (flag) {
          newMenu.push(item1);
        }
      }
      state.menuAll = newMenu;
      setStore({name: 'menuAll', content: state.menuAll})
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      setRefreshToken(refreshToken)
      state.refreshToken = refreshToken;
      setStore({name: 'refreshToken', content: state.refreshToken})
    },
    SET_TENANT_ID: (state, tenantId) => {
      state.tenantId = tenantId;
      setStore({name: 'tenantId', content: state.tenantId})
    },
    SET_USER_INFO: (state, userInfo) => {
      if (validatenull(userInfo.avatar)) {
        userInfo.avatar = "/img/bg/img-logo.png";
      }
      state.userInfo = userInfo;
      setStore({name: 'userInfo', content: state.userInfo})
    },
    SET_ROLES: (state, roles) => {
      let role = {
        administrator: roles.includes('administrator'),
        admin:roles.includes('admin'),
        operator: roles.includes('operator') || roles.includes('customer_manager') || roles.includes('sales_manager'),//运营级别的人员
        adv_operator: roles.includes('operator'),//广告主市场运营
        agc_sales_manager: roles.includes('sales_manager'),//代理商销售经理
        agc_customer_manager: roles.includes('customer_manager'),//代理商客户经理
        optimizer:roles.includes('optimizer'),
        designer_manager: roles.includes('designer_manager'),
        designer:roles.includes('designer'),
        analyst:roles.includes('analyst'),
        auditor:roles.includes('auditor'),
        view_agency:roles.includes('admin') || roles.includes('media_operator') || roles.includes('finance'),
      }
      state.roles = role;
      setStore({name: 'roles', content: state.roles})
    },
    SET_PERMISSION: (state, permission) => {
      let result = [];
      function getCode(list) {
        if (list) {
          list.forEach(ele => {
            if (typeof (ele) === 'object') {
              const children = ele.children;
              const code = ele.code;
              if (children) {
                getCode(children)
              } else {
                result.push(code);
              }
            }
          })
        }
      }

      getCode(permission);
      state.permission = {};
      result.forEach(ele => {
        state.permission[ele] = true;
      });
      setStore({name: 'permission', content: state.permission})
    }
  }

}
export default user
